package com.code.springsecurityoauth.security;

import com.code.springsecurityoauth.LoginType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class MyAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        log.info("登录失败");
        if (LoginType.JSON.equals("JSON")) {
            // 如果请求的是json数据，则做如下处理
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(exception.getMessage()));
            // 若有异常，打印到控制台，方便查看
            System.out.println(exception);
        } else {
            // 如果请求的是页面跳转，则走父类的实现，父类默认实现就是页面跳转
            // 还记得之前没有配置这个失败处理器的时候吧，我们请求某个url，会先跳到登录页面，认证后重新跳到原来的请求url上，也就是父类的默认实现
            super.onAuthenticationFailure(request, response, exception);
        }

    }
}
